package com.tao.filter;

import com.alibaba.fastjson.JSON;

import com.tao.entity.LoginUser;
import com.tao.enums.AppHttpCodeEnum;
import com.tao.utils.JwtUtils;
import com.tao.utils.RedisCache;
import com.tao.utils.WebUtils;
import com.tao.vo.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 季伟
 * 不选择实现filter接口是因为如果直接实现filter接口会存在一个请求多次访问这个过滤器
 * 因此选择继承OncePerRequestFilter保证一次请求只会经过一次这个过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        /*如果为空就不把用户信息提取到securityContext中
        从而使后者的filter进行判断请求是否为匿名或者开放的接口
        若不是就交给springSecurity进行异常处理
         */
        if (StringUtils.isEmpty(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return ;
        }
        String userId =null;
        //这里发生异常不会由spring boot的controller统一异常处理进行处理因为此时还在过滤器中尚未进入controller层
        try{
            Claims claims = JwtUtils.parseJWT(token);
            userId = claims.getSubject();
        }catch (Exception e){
            e.printStackTrace();
//            直接将异常抛出
//            throw new RuntimeException("用户未登录");
//            //直接交给spring Security处理异常，且异常是用户认证异常
//            filterChain.doFilter(httpServletRequest,httpServletResponse);
//            return;
            /* token超时或者非法
             * 自定义响应内容，没有进行进一步的过滤也就是不进入security的过滤链直接自己写响应体返回回去
             */
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.writeJsonDataToResponse(httpServletResponse, JSON.toJSONString(responseResult));
            return;
        }
        //根据token解析出来的值获取用户信息
        String redisKey = "login:"+userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
//            throw new RuntimeException("用户未登录");
//            //直接交给spring Security处理异常，且异常是用户认证异常
//            filterChain.doFilter(httpServletRequest,httpServletResponse);
//            return;
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.writeJsonDataToResponse(httpServletResponse,JSON.toJSONString(responseResult));
            return;
        }
        if(!loginUser.getToken().equals(token)){
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.writeJsonDataToResponse(httpServletResponse, JSON.toJSONString(responseResult));
            return;
        }
        //将用户信息存到SecurityContextHolder中
        //根据获取的信息创建一个表示经过已验证的authentication对象,在该构造函数中会调用super.setAuthenticated(true)
        // 将用户的权限信息存到authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
